import { useEffect, useState } from 'react';
import { redirectTo } from '@tarojs/taro';
import { Button, Animate } from '@nutui/nutui-react-taro';
import { Image, Text, View } from '@tarojs/components';
import './index.less';
import Navbar from '@/components/Navbar';
import AuthConstant from '@/constant/AuthConstant';
import authStore from '@/stores/AuthStore';
import useLandlord from '@/hooks/useLandlord';
import useTenant from '@/hooks/useTenant';
import ImageConstant from '@/constant/ImageConstant';

export default function IdentityComp() {
  const [isShow, setIsShow] = useState(false);

  const toHome = (identity: typeof AuthConstant.LANDLORD | typeof AuthConstant.TENANT) => {
    // 跳转之前先进行判断，若选择的当前身份与上一次身份相同，则不清除登录态；反之则清除
    if (authStore.preIdentity !== identity) { // 说明与上次选择的身份不一样
      if (authStore.preIdentity === AuthConstant.LANDLORD) { // 清除房东登录态
        useLandlord().landlordLogout();
      } else if (authStore.preIdentity === AuthConstant.TENANT) { // 清除租客登录态
        useTenant().tenantLogout();
      }
    }
    authStore.setIdentityState(identity);
    redirectTo({url: '/pages/tabbar/index'});
  };

  useEffect(() => {
    if (authStore.identity) {
      redirectTo({url: '/pages/tabbar/index'});
      return;
    }
    setIsShow(true);
  }, []);

  return (
    <>
      { isShow ? (
        <Navbar>
          <View className='identity-page'>
            <View className='tenant-container'>
              <Image
                src={ `${ImageConstant.SERVER_ROOT}/common/tenant.png` }
                mode='widthFix'
                style={ {width: '200px'} }
              />
              <Animate type='breath' loop>
                <Button
                  type='primary'
                  size='large'
                  className='btn'
                  onTap={ () => toHome(AuthConstant.TENANT) }
                >
                  我是租客
                </Button>
              </Animate>
            </View>
            <View className='flex items-center'>
              <View className='split-line'/>
              <Text className='split-text'>或者</Text>
              <View className='split-line'/>
            </View>
            <View className='landlord-container'>
              <Image
                src={ `${ImageConstant.SERVER_ROOT}/common/landlord.png` }
                mode='widthFix'
                style={ {width: '200px'} }
              />
              <Animate type='breath' loop>
                <Button
                  type='primary'
                  size='large'
                  className='btn'
                  onTap={ () => toHome(AuthConstant.LANDLORD) }
                >
                  我是房东
                </Button>
              </Animate>
            </View>
          </View>
        </Navbar>
      ) : null }
    </>
  );
}
